package com.financing.wap.web.controller.api;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.BizEnums;
import com.financing.wap.common.BizEnums.ActivityEnums;
import com.financing.wap.common.BizEnums.ValidFlag;
import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.FpClientActivityDTO;
import com.financing.wap.dto.ShopperUserInfoDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IFpClientActivityService;
import com.financing.wap.service.IShopperUserInfoService;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

@Controller("fpClientActivityController")
@RequestMapping("/api/fpClientActivity")
public class FpClientActivityController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IFpClientActivityService fpClientActivityService;
	
	@Autowired
	private IUserService userService;
	@Autowired
	private IShopperUserInfoService shopperUserInfoService;
	/***
	 * 
	
	* @Title: list
	
	* @Description: 当前用户活动列表
	
	* @param @param request
	* @param @param fpClientActivity
	* @param @param pager
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/listFpClientActivity")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, FpClientActivityDTO fpClientActivity,Pager pager){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query fpClientActivity list begin .......");
			String loginMobile=request.getParameter("mobile");
			
			if(StringUtils.isBlank(loginMobile)){
				//查询当前用户的活动
				UserDTO u=SessionUtil.getSession().getUser();
				if(null == u){
					result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
					result.setStatus(ResultMap.STATUS.FAILE);
					return result;
				}
				fpClientActivity.setUserId(u.getLoginName());
			}else{
				fpClientActivity.setUserId(loginMobile);
			}
			
			fpClientActivity.setBegin(pager.getStartIndex());
			fpClientActivity.setPageSize(pager.getPageSize());
			fpClientActivity.setDeleteTag("1");
			int count = fpClientActivityService.queryListCount(fpClientActivity);
			
			pager.setTotalCount(count);
			
			List<FpClientActivityDTO> fpClientActivityList = null;
			
			if(count > 0){
				fpClientActivityList = fpClientActivityService.queryList(fpClientActivity);
				for (FpClientActivityDTO fpClientActivityDTO : fpClientActivityList) {
					Date activityEndDate = fpClientActivityDTO.getActivityEndDate();
					if(new Date().after(activityEndDate)){
						fpClientActivityDTO.setFlagEnd(true);
					}else{
						fpClientActivityDTO.setFlagEnd(false);
					}
				}
			}else{
				fpClientActivityList = Collections.emptyList();
			}
			result.setAttribute("pager", pager);
			result.setAttribute("list", fpClientActivityList);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query fpClientActivity list end .......");
		}catch(Exception e){
			log.error("query fpClientActivity error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	/***
	 * 
	
	* @Title: add
	
	* @Description：理财师添加活动
	
	* @param @param request
	* @param @param fpClientActivity
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/addFpClientActivity")
	@ResponseBody
	public ResultMap add(HttpServletRequest request, FpClientActivityDTO fpClientActivity){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("add fpClientActivity  begin .......");
			// 获取登录人userId
			UserDTO u = this.getSession().getUser();
			if(null == u){
				result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			fpClientActivity.setUserId(u.getLoginName());
			
			// 其他参数校验
			boolean validate = validate(fpClientActivity, result);
			
			if(!validate){
				return result;
			}
			
			int id = fpClientActivityService.insert(fpClientActivity);
			result.setAttribute("id", id);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("add fpClientActivity list end .......");
		}catch(Exception e){
			e.printStackTrace();
			log.error("add fpClientActivity error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}

	public boolean validate(FpClientActivityDTO fpClientActivity, ResultMap result) {
		String title = fpClientActivity.getActivityTitle();//主题
		String address = fpClientActivity.getActivityAddress();//地址
		String startDateStr = fpClientActivity.getActivityStartDateStr();//开始时间
		String endDateStr = fpClientActivity.getActivityEndDateStr();//结束时间
		String activityType=fpClientActivity.getActivityType();//活动
		
		if(StringUtil.isNullOrEmptyNStr(title,startDateStr,endDateStr,activityType)){
			result.setStatus(ResultMap.STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			return false;
		}
		boolean typeIsOnline= StringUtils.isNotBlank(activityType)
				&&activityType.equals(ActivityEnums.ACTIVITY_TYPE_ONLINE);
		if(typeIsOnline){
			fpClientActivity.setActivityType(ActivityEnums.ACTIVITY_TYPE_ONLINE);
		}else{
			fpClientActivity.setActivityType(ActivityEnums.ACTIVITY_TYPE_LINE);
		}
		if(activityType.equals(ActivityEnums.ACTIVITY_TYPE_LINE)&&StringUtils.isBlank(address)){
			result.setStatus(ResultMap.STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			return false;
		}
		
		Date startDate=null;
		Date endDate=null;
		try {
			startDate = DateUtil.parseDateString(startDateStr, "yyyy-MM-dd HH:mm:ss");
			endDate = DateUtil.parseDateString(endDateStr, "yyyy-MM-dd HH:mm:ss");
			if(startDate.after(endDate)){//开始时间必须小于结束时间
				result.setStatus(ResultMap.STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_START_LESS_END_DATE);
				return false;
			}
		} catch (Exception e) {
			result.setStatus(ResultMap.STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_DATE_FOMART_ERROR);
			return false;
		}
		
		
		fpClientActivity.setActivityStartDate(startDate);
		fpClientActivity.setActivityEndDate(endDate);
		
		return true;
	}
	
	
	@RequestMapping("/detailFpClientActivity")
	@ResponseBody
	public ResultMap detail(HttpServletRequest request, FpClientActivityDTO fpClientActivity){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query detail fpClientActivity  begin .......");
			
			Integer id = fpClientActivity.getId();
			
			if(id==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			FpClientActivityDTO dto = fpClientActivityService.loadById(id);


			Date activityEndDate = dto.getActivityEndDate();
			if(new Date().after(activityEndDate)){
				dto.setFlagEnd(true);
			}else{
				dto.setFlagEnd(false);
			}
			try {
//				UserDTO u=new UserDTO();
//				u.setLoginName(dto.getUserId());
//				UserDTO uLoginName = userService.queryUserLoginName(u);
//				if(uLoginName.getId()!=null){
//					dto.setUserName(uLoginName.getuRealName());
//				}
				//活动发起人查询店铺名称 如果为空则为电话号码
				ShopperUserInfoDTO sui = new ShopperUserInfoDTO();
				sui.setUserPhone(dto.getUserId());
				
				List<ShopperUserInfoDTO> l= shopperUserInfoService.queryList(sui);
				if(l.size()==1){
					dto.setUserName(l.get(0).getUserName());
				}else{
					dto.setUserName(dto.getUserId());
				}
				
			} catch (Exception e) {
				log.error("detail fpClientActivity error!",e);
			}
			
			result.setAttribute("dto",dto);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query detail fpClientActivity  end .......");
		}catch(Exception e){
			log.error("query detail fpClientActivity error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	@RequestMapping("/updateFpClientActivity")
	@ResponseBody
	public ResultMap update(HttpServletRequest request, FpClientActivityDTO fpClientActivity){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("update fpClientActivity  begin .......");
			// 获取登录人userId
			UserDTO u = this.getSession().getUser();
			if(null == u){
				result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			fpClientActivity.setUserId(u.getLoginName());
			
			Integer id = fpClientActivity.getId();
			
			if(id==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			//参数校验
			boolean validate = validate(fpClientActivity, result);
			if(!validate){
				return result;
			}
			
			fpClientActivityService.update(fpClientActivity);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("update fpClientActivity list end .......");
		}catch(Exception e){
			log.error("update fpClientActivity error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	@RequestMapping("/deleteFpClientActivity")
	@ResponseBody
	public ResultMap delete(HttpServletRequest request, FpClientActivityDTO fpClientActivity){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("delete fpClientActivity  begin .......");
			
			Integer id = fpClientActivity.getId();
			
			if(id==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			FpClientActivityDTO d=fpClientActivityService.loadById(id);
			if(d.getId()==null){
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}
			d.setDeleteTag("2");
			fpClientActivityService.update(d);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("delete fpClientActivity list end .......");
		}catch(Exception e){
			log.error("delete fpClientActivity error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
}
